import React, { Component } from 'react'
import './Shop.less'
import Header from '../../components/Header/Header'
import { reqcartlist,reqcartdelete,reqcartedit } from '../../http/api'
import { SwipeAction,Stepper,Dialog, Toast } from 'antd-mobile'
import yImg from '../../assets/img/y.jpeg'
import nImg from '../../assets/img/n.jpeg'
import { $pre } from '../../http/http'
import { Link } from 'react-router-dom'
export default class Shop extends Component {
  constructor(props) {
    super(props)
    let coupon = this.props.location.state?.couponInfo ? this.props.location.state?.couponInfo : {};
    console.log(coupon);
    this.state = {
      list: [],
      allChecked:false,
      couponInfo:coupon,
    }
    this.isEdit=true;
  }
  componentDidMount() {
    this.getList();
    
    // this.setState({
    //   couponInfo,
    // })
  }
  //获取列表
  async getList() {
    let { uid } = JSON.parse(localStorage.getItem('isLogin'));
    let { data: res } = await reqcartlist({ uid });
    if (res.code === 200) {
      let arr0 = res.list[0].content ? res.list[0].content : [];
      let arr1 = res.list[1].content ? res.list[1].content : [];
      let arr = [...arr0, ...arr1];
      arr.forEach(item=>{
        let obj = this.state.list.find(i=> i.id === item.id);
        item.isChecked = obj ? obj.isChecked : false;
      })
      this.setState({
        list: arr,
        allChecked: arr.length > 0 ? arr.every(item=>item.isChecked):false
      }, () => {
        this.isEdit=true;
      })
    }
  }
  //删除
  async delCart(id){
    let {data:res} = await reqcartdelete({id});
    if(res.code === 200){
      Toast.show({content:'删除成功'});
      this.getList();
    }
  }
  //修改
  async editCart(v,id){
    if(this.isEdit){
      this.isEdit=false;
      let {num}= this.state.list.find(item => item.id===id);
      let res;
      if(num < v){
          //加
         res = await reqcartedit({id,type:2});
      }else{
        //减
        res = await reqcartedit({id,type:1});
      }
      if(res.data.code === 200){
        this.getList();
      }
    }
  }
  //点击单选按钮
  changeOne(id){
    let {list} = this.state;
    let index = list.findIndex(item=>item.id === id);
    list[index].isChecked = !list[index].isChecked;
    this.setState({
      list,
      allChecked:list.every(item=>item.isChecked)
    })
  }
  //点击全选按钮
  changeAll(){
    let {allChecked:flag} = this.state;
    this.setState({
      allChecked:!flag,
    },()=>{
      this.state.list.forEach(item=>{
        item.isChecked=this.state.allChecked;
      });
      this.setState({
        list:this.state.list
      })
    })
  }
  render() {
    let {list,allChecked,couponInfo}  = this.state;
    let totalPrice = list.reduce((a,b)=>{
      if(b.isChecked){
          return a+b.num*b.price
      }
      return a
    },0)
    return (
      <div className='shop'>
        <Header title='购物车' back></Header>
        <div className="list">
          {list.length>0 ? ( list.map(item =>(<SwipeAction
          key={item.id}
            rightActions={[
              {
                key: 'delete',
                text: '删除',
                color: 'danger',
                onClick: async () => {
                  let result =  await Dialog.confirm({
                    content: '确定要删除吗？',
                  });
                  if(result){
                    this.delCart(item.id);
                  }
                },
              },
            ]}
          >
            <div className="item">
              <img
                onClick={()=>this.changeOne(item.id)}
                src={item.isChecked ? yImg : nImg}
                className="checkbox"
                alt=""
              />
              <img
                className="img"
                src={$pre + item.img}
                alt=""
              />
              <div className="right">
                <h3>商品名称:{item.goodsname}</h3>
                <div>单价:{item.price}</div>
                <div>数量：x {item.num}</div>
                <div>
                  <Stepper onChange={(v)=>this.editCart(v,item.id)} inputReadOnly value={item.num} min={1}/>
                </div>
              </div>
            </div>
          </SwipeAction>))):(<div>暂无数据</div>) }
          
        </div>
        <div className="footer">
          <div className="allChecked" onClick={()=>{this.changeAll()}}>
            <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
            全选
          </div>
          <div className='couponBox'>
            <Link to={'/coupon'}>优惠券</Link>
            {couponInfo.title ? (<span>-{couponInfo.money}</span>) : (null)}
          </div>
          <div className="allPrice">￥{totalPrice === 0 ? totalPrice : (totalPrice - (couponInfo.money || 0))}</div>
        </div>
      </div>
    )
  }
}
